package cn.chengpengper.rpc.serialization.jdk;

import cn.chengpengper.rpc.common.exception.SerializerException;
import cn.chengpengper.rpc.serialization.api.Serialization;
import cn.chengpengper.rpc.spi.annotation.SpiClass;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Objects;

/**
 * @author chengpeng.hu
 */
@Slf4j
@SpiClass
public class JdkSerialization implements Serialization {
    @Override
    public <T> byte[] serialize(T obj) {
        log.info("execute jdk serialize...");
        if (Objects.isNull(obj)) {
            throw new SerializerException("serialize object is null");
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(os);
            out.writeObject(obj);
            return os.toByteArray();
        } catch (IOException e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        log.info("execute jdk deserialize...");
        if (Objects.isNull(data)) {
            throw new SerializerException("deserialize data is null");
        }
        try {
            ByteArrayInputStream is = new ByteArrayInputStream(data);
            ObjectInputStream in = new ObjectInputStream(is);
            return ((T) in.readObject());
        } catch (Exception e) {
            throw new SerializerException(e.getMessage(), e);
        }
    }
}
